using System;
using System.Reflection;
using System.Web.UI;
using Sedna.Core.Controller;
using Sedna.Core.Support;
using log4net;

namespace Sedna.Core.Controls.Support
{
	public class ControlBuilder
	{
		private static ILog log = LogManager.GetLogger(typeof(System.Web.UI.ControlBuilder));

		public static Control BuildControl(IConfiguration configuration)
		{

			Assert.IsNotNull(configuration, "configuration parameter must not be null");

			Type controlType = configuration.ControlType;
			if(controlType == null)
			{
				log.Error("unable to instantiate a control, controlType is null. configuration: " + configuration.ObjectName);
				throw new ControllerConfigurationException("unable to instantiate a control, controlType is null. configuration: " + configuration.ObjectName);
			}

			ConstructorInfo constructor = controlType.GetConstructor(new Type[]{typeof(IConfiguration)});
			if(constructor == null)
			{
				log.Error("unable to locate a constructor that accepts an IConfiguration as a parameter. controlType=" + controlType + "; configuration: " + configuration.ObjectName);
				throw new ControllerConfigurationException("unable to locate a constructor that accepts an IConfiguration as a parameter. controlType=" + controlType + "; configuration: " + configuration.ObjectName);
			}

			try
			{
				return (Control)constructor.Invoke(new object[]{configuration});
			}
			catch(Exception ex)
			{
				log.Error("unable to instantiate a control. controlType=" + controlType + "; configuration: " + configuration.ObjectName, ex);
				throw;
			}

		}
	}
}
